<template>
    <div>
    <el-card>
        <!-- 搜索区域 -->
        <el-row :gutter="24">
            <el-col :span="7">
            <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" class="input-with-select" clearable
            @clear =" UserSelect()" @keyup.enter.native=" UserSelect()">
                <el-select v-model="queryInfo.select" slot="prepend" placeholder="请选择" style="width:120px">
                    <el-option label="姓名" value="0"></el-option>
                    <el-option label="用户名" value="1"></el-option>
                    <el-option label="联系电话" value="2"></el-option>
                    <!-- <el-option label="设备编码" value="devnum"></el-option> -->
                </el-select>
                <el-button slot="append" type="primary" icon="el-icon-search" @click=" UserSelect()" size="mini"></el-button>
            </el-input>
            </el-col>

            <el-col :span="2">
            <el-popover style="margin-top:10px;" trigger="click" width="800">
                <el-button slot="reference" >高级检索</el-button>
                <el-form label-position="left" ref="selectFormRef" :model="queryInfo">
                    <el-row :gutter="10">
                        <el-col :span="3">
                            <el-form-item label="性别" prop="sex">
                                <el-radio-group v-model="queryInfo.sex" style="width:40%">
                                    <el-radio label="男"></el-radio>
                                    <el-radio label="女"></el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="年龄" prop="age_lower" >
                                <el-input style="width:50px" v-model="queryInfo.age_lower"></el-input> - 
                                <el-input style="width:50px" v-model="queryInfo.age_upper"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="身高" prop="height_lower">
                                <el-input style="width:60px" v-model="queryInfo.height_lower"></el-input>cm - 
                                <el-input style="width:60px" v-model="queryInfo.height_upper"></el-input>cm
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="体重" prop="weight_lower">
                                <el-input style="width:50px" v-model="queryInfo.weight_lower"></el-input>kg - 
                                <el-input style="width:50px" v-model="queryInfo.weight_upper"></el-input>kg
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="10">
                        <el-col :span="8">
                            <el-form-item label="测量模式" prop="measureMode">
                                <el-input style="width:70%" v-model="queryInfo.measureMode"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="医生" prop="doctor">
                                <el-input style="width:70%" v-model="queryInfo.doctor"></el-input>
                            </el-form-item>
                        </el-col>
                         <el-col :span="6" style="margin-left:160px;">
                            <el-button type="primary" @click="UserSelect()">筛选</el-button>
                            <el-button type="info" @click="resetForm()">重置</el-button>
                        </el-col>
                    </el-row>
                    <!-- <el-row :gutter="20"> -->
                        <!-- <el-col :span="8" style="magrin-left:20px;">
                            <el-date-picker type="datetime" placeholder="开始日期" value-format="yyyy-MM-dd HH:mm:ss" 
                            v-model="queryInfo.beginTime" :picker-options="startPicker" style="width: 100%;"></el-date-picker>
                        </el-col>
                        <el-col class="line" :span="1">_</el-col>
                        <el-col :span="8">
                            <el-date-picker type="datetime" placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
                            v-model="queryInfo.endTime" :picker-options="startPicker" style="width: 100%;"></el-date-picker>
                        </el-col> -->
                       
                    <!-- </el-row> -->
                </el-form>
        </el-popover>
            </el-col>

            <el-col :span="4" >
                <el-date-picker type="datetime" placeholder="开始日期" value-format="yyyy-MM-dd HH:mm:ss" 
                v-model="queryInfo.beginTime" :picker-options="startPicker" style="width: 100%;"></el-date-picker>
            </el-col>
            
            <el-col :span="4">
                <el-date-picker type="datetime" placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss"
                v-model="queryInfo.endTime" :picker-options="startPicker" style="width: 100%;"></el-date-picker>
            </el-col>
            <el-col :span="2">
                <el-button type="primary" @click="UserSelect()">筛选</el-button>
                <!-- <el-button type="info" @click="resetForm()">重置</el-button> -->
            </el-col>
            <el-col :span="2">
                <el-button icon="iconfont icon-excel" style="height:40px;margin-left: -30px;" @click="downloadExcel()">导出Excel</el-button>
            </el-col>
            <el-col :span="2" :offset="1">
                <el-button type="primary" icon="el-icon-download" style="height:40px;margin-left: -100px;" @click="downloadBatchOriginalFootZipFile()">源文件下载</el-button>
            </el-col>
         </el-row>
        
        <el-table :data="patientList" border stripe element-loading-text="拼命加载中" style="margin-top:10px" 
        :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}">
            <el-table-column type="index" :index="indexMethod"></el-table-column><!--  索引页  -->
            <el-table-column label="姓名" prop="name"></el-table-column><!--  索引页  -->
            <el-table-column label="性别" prop="sex" width="43px"></el-table-column><!--  索引页  -->
            <el-table-column label="年龄" prop="age" width="43px"></el-table-column><!--  索引页  -->
            <el-table-column label="出生日期" prop="birthDate" width="136px"></el-table-column><!--  索引页  -->
            <el-table-column label="身高" prop="height" width="50px"></el-table-column><!--  索引页  -->
            <el-table-column label="体重" prop="weight" width="50px"></el-table-column><!--  索引页  -->
            <el-table-column label="联系方式" prop="phone" width="113px"></el-table-column><!--  索引页  -->
            <el-table-column label="测量模式" prop="measureMode" width="100px"></el-table-column><!--  索引页  -->
            <el-table-column label="手术史" prop="historyofsurgery"></el-table-column>
            <el-table-column label="上传时间" prop="createTime" width="200px"></el-table-column>
            <el-table-column label="医生" prop="doctor"></el-table-column>
            <el-table-column label="机构" prop="orgName"></el-table-column>
            <el-table-column label="设备编号" prop="devNum"  width="226px"></el-table-column>
            <el-table-column label="操作" width="175px">
                <template slot-scope="scope">
                    <el-tooltip class="item" effect="dark" content="下载步态分析" placement="top">
                        <el-button type="primary" icon="el-icon-download" size="mini" @click="downloadReport1(scope.row)"
                         v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="正在下载，请稍候"></el-button>
                    </el-tooltip>
                    <el-tooltip class="item" effect="dark" content="下载平衡测试" placement="top">
                        <el-button type="primary" icon="el-icon-download" size="mini" @click="downloadReport2(scope.row)"
                         v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="正在下载，请稍候"></el-button>
                    </el-tooltip>
                    <el-popconfirm title="选择预览的报告" confirm-button-text='步态分析' cancel-button-text='平衡测试' cancel-button-type='Primary'
                     @onConfirm="previewReport1(scope.row)" @onCancel='previewReport2(scope.row)' >
                        <el-button type="primary" icon="el-icon-s-order"  size="mini" slot="reference" style="margin-left:10px" ></el-button>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pageNum"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="queryInfo.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>

    </el-card>
    </div>
</template>

<script>
import { getAllPatientsApi, downloadGaitApi, downloadBalanceApi,
 calculatedDataFootExcelApi, getDownloadTimesApi, advancedQueryApi,downloadBatchOriginalFootZipFileApi} from '@/api/data/footData.js'
export default {
    data(){
        return{
            queryInfo:{
                query:"",
                select:"",
                name:"",
                username:"",
                sex:"",
                phone:"",
                age_lower:"",
                age_upper:"",
                height_lower:"",
                height_upper:"",
                weight_lower:"",
                weight_upper:"",
                measureMode:"",
                doctor:"",
                beginTime:"",
                endTime:"",
                orgName:"",
                pageNum:1,    //当前页数
                pageSize:10  //每页最大数
            },
            patientList:[],  //用户列表
            total:0, //总记录数
            select:"姓名",    //查询类别
            fullscreenLoading: false,
            // queryDate:{
            //   beginTime:"",
            //   endTime:"",
            // },
            downloadTimes:5,
            startPicker:{
                disabledDate(time) {
                return time.getTime() > Date.now();
                },
            },
            advancedSearch:{
                name:"",
                username:"",
                sex:"",
                age_lower:"",
                age_upper:"",
                height_lower:"",
                height_upper:"",
                weight_lower:"",
                weight_upper:"",
                measureMode:"",
                doctor:"",
                beginTime:"",
                endTime:"",
                pageNum:1,    //当前页数
                pageSize:10  //每页最大数
            }
        }
    },
    created(){
       this.getPatientList();
    },
    methods: {
        resetForm(){
            this.$refs.selectFormRef.resetFields()
            this.queryInfo.age_upper = ""
            this.queryInfo.height_upper = ""
            this.queryInfo.weight_upper = ""
            this.queryInfo.endTime = ""
            this.queryInfo.beginTime = ""
            this.queryInfo.name = ""
            this.queryInfo.username = ""
            this.queryInfo.phone = ""
            this.queryInfo.pageNum=1;
            this.getPatientList()
        },
        //id
        indexMethod(index){
            return (this.queryInfo.pageNum - 1) * this.queryInfo.pageSize + index + 1
        },
        getPatientList(){
            getAllPatientsApi(this.queryInfo).then(res=>{
                this.patientList = res.data.patients;//一页的所有病人
                this.total = res.data.total;//当前的页数
              
                //this.$message.success(res.message)
            })
        },
        //用户筛选
        UserSelect(){
            if(this.queryInfo.select === "0"){
                this.queryInfo.username = ""
                this.queryInfo.name = this.queryInfo.query
                this.queryInfo.phone = "" 
            }else if(this.queryInfo.select === "1"){
                this.queryInfo.name = ""
                this.queryInfo.username = this.queryInfo.query
                this.queryInfo.phone =""
            }else if(this.queryInfo.select ==="2"){
                this.queryInfo.name = ""
                this.queryInfo.username = ""
                this.queryInfo.phone  = this.queryInfo.query
            }
                this.queryInfo.pageNum=1
              getAllPatientsApi(this.queryInfo).then(res=>{
                this.patientList = res.data.patients;
                this.total = res.data.total;
                //this.$message.success(res.message)
            })
        },
        //最大数
        handleSizeChange(newSize){
            this.queryInfo.pageSize = newSize;
            this.getPatientList();
        },
        //pageNum的触发动作
        handleCurrentChange(newPage){ 
            this.queryInfo.pageNum = newPage;
            this.getPatientList();
        },
        downloadReport1(params){
            var fileName = this.getFileName(params,"步态分析")
            console.log(fileName);
            this.fullscreenLoading = true;
            setTimeout(()=>{
                this.fullscreenLoading = false
            },10000)
            downloadGaitApi(params.id).then(res=>{
                this.download(res,fileName)
            }).catch(()=>{
                this.fullscreenLoading = false
            })
        },
        downloadReport2(params){
            var fileName = this.getFileName(params,"平衡分析")
            console.log(fileName);
            this.fullscreenLoading = true;
            setTimeout(()=>{
                this.fullscreenLoading = false
            },10000)
            downloadBalanceApi(params.id).then(res=>{
                this.download(res,fileName)
            }).catch(()=>{
                this.fullscreenLoading = false
            })
        },
        // getDownloadTimesApi(res){
        //     this.getDownloadTimes=res.
        // },
        getFileName(params,fileType){
            console.log(1111111);
            if(fileType === "步态分析"){
                let str = params.fileGaitPath
                let strList = new Array()
                strList = str.split("\\")
                let name = strList[strList.length-1]
                let nameList = new Array()
                nameList = name.split(".")
                return nameList[0]
            }else if(fileType === "平衡分析"){
                let str = params.fileBalancePath
                let strList = new Array()
                strList = str.split("\\")
                let name = strList[strList.length-1]
                let nameList = new Array()
                nameList = name.split(".")
                return nameList[0]
            }
        },
        download(res, fileName) {
            if(!res) {
                return ;
            }
            console.log(res);
            const  blob = new Blob([res], {type: 'application/pdf'});
            let url = window.URL.createObjectURL(blob);
            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.download = decodeURIComponent(fileName);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url); // 释放掉blob对象
            this.fullscreenLoading = false;
        },
        previewReport1(params){
            this.fullscreenLoading = true
            setTimeout(() => {
                this.fullscreenLoading = false
                }, 10000);
            
            downloadGaitApi(params.id).then(res => {
                const  blob = new Blob([res], {type: 'application/octet-stream'});
               const pdfUrl = window.URL.createObjectURL(blob);
                window.open('../pdfjs/web/viewer.html?file=' + encodeURIComponent(pdfUrl));
               
            }).catch(()=>{
                this.fullscreenLoading = false
            });
            this.fullscreenLoading = false
             window.URL.revokeObjectURL(pdfUrl);
        },
        previewReport2(params){
            this.fullscreenLoading = true
            setTimeout(() => {
                this.fullscreenLoading = false
                }, 10000);
            downloadBalanceApi(params.id).then(res => {
                const  blob = new Blob([res], {type: 'application/octet-stream'});
                const pdfUrl = window.URL.createObjectURL(blob);
                console.log(pdfUrl);
                window.open('../pdfjs/web/viewer.html?file=' + encodeURIComponent(pdfUrl));
               
            }).catch(()=>{
                this.fullscreenLoading = false
            });
            this.fullscreenLoading = false
             window.URL.revokeObjectURL(pdfUrl);
        },
        // shaixuan(){
        //     if (!this.queryInfo.beginTime || !this.queryInfo.endTime) {
        //         this.$message.warning("请输入起始日期")
        //         return;
        //     }else if(this.queryInfo.beginTime > this.queryInfo.endTime){
        //         this.$message.warning("结束日期不能早于开始日期")
        //         return;
        //     }   
        // },
        async downloadExcel(){
            // getDownloadTimes();
            // if (!this.queryInfo.beginTime || !this.queryInfo.endTime) {
            //     this.$message.warning("请输入起始日期")
            //     return;
            // }else 
            if(this.queryInfo.beginTime > this.queryInfo.endTime){
                this.$message.warning("结束日期不能早于开始日期")
                return;
            }
            const confirmResult = await this.$confirm('是否下载Excel文件, 剩余' + this.downloadTimes + "次", '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                })
                .then( this.downloadTimes > 0 ? this.downloadTimes-- : this.$confirm("下载Excel文件次数已经用尽,请联系超级管理员"))
                .catch(err => err)
            // 确认为confirm 取消为 cancel
            if(confirmResult != 'confirm'){
                return this.$message.info("已取消下载");
            }else {
                 console.log("excel:"+this.queryInfo)
                calculatedDataFootExcelApi(this.queryInfo).then(res => {
                    var excel = new Object();
                    
                    const sheet1 = res.data.excelFootCounts
                    const sheet2 = null;
                    excel.sheet1 = sheet1;
                    excel.sheet2 = sheet2;
                // this.excelData.sheet1 = this.excelFootCounts;
                    const data = excel;

                    const fileName = this.queryInfo.beginTime + this.queryInfo.endTime
                    if(this.downloadTimes > -1){
                        this.$toExcel({data, fileName})
                    }
                })
            }
        },
        advancedSearchMethod(){
            console.log(this.advancedSearch)
            advancedQueryApi(this.advancedSearch).then(res =>{
                this.patientList = res.data.patients
                this.total = res.data.total
                // console.log(res)
            })
        },
        downloadBatchOriginalFootZipFile(){
            //  if (!this.queryInfo.beginTime || !this.queryInfo.endTime) {
            //     this.$message.warning("请输入起始日期")
            //     return;
            // }else 
            if(this.queryInfo.beginTime > this.queryInfo.endTime){
                this.$message.warning("结束日期不能早于开始日期")
                return;
            }
            this.fullscreenLoading = true;
            
             console.log("FootZip:"+this.queryInfo)
            downloadBatchOriginalFootZipFileApi(this.queryInfo).then(res => {
                    console.log(res);
                const fileName = '步态分析原始数据' + this.queryInfo.beginTime + this.queryInfo.endTime;
                this.downloadZip(res,fileName)
                this.fullscreenLoading = false
            }).catch(()=>{
                this.fullscreenLoading = false
            })
        },
        downloadZip(res,fileName){
            if(!res) {
                return ;
            }
            const  blob = new Blob([res], {type: 'application/zip'});
            let url = window.URL.createObjectURL(blob);

            let link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.download = decodeURIComponent(fileName + ".zip");
    
            document.body.appendChild(link);
            link.click();
            window.URL.revokeObjectURL(url); // 释放掉blob对象
        
            document.body.removeChild(link);
            this.fullscreenLoading = false;
        },
    },

}
</script>

<style lang="less" scoped>
.el-breadcrumb{
    margin-bottom: 15px;
    font-size: 17px;
}
.el-select{
    width: 100px;
}
.input-with-select{
    background-color: #fff;
}
.line{
    width: 20px;
}
</style>
